<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="X-UA-Compatible" content="ie=edge" />
	<title>JS 实现 Checkbox 中按住 Shift 的多选功能</title>

	<style type="text/css">
		html {
			font-family: sans-serif;
			background: #FFC600;
		}

		.inbox {
			max-width: 400px;
			margin: 50px auto;
			background: white;
			border-radius: 5px;
			box-shadow: 10px 10px 0 rgba(0,0,0,0.1);
		}

		.item {
			display: flex;
			align-items: center;
			border-bottom: 1px solid #f1f1f1;
		}

		.item:last-child {
			border-bottom: 0;
		}

		input:checked + p {
			background: #f9f9f9;
			text-decoration: line-through;
		}

		input[type='checkbox'] {
			margin: 20px;
		}

		p {
			margin: 0;
			padding: 20px;
			transition: background 0.2s;
			flex: 1;
			font-family: 'helvetica neue';
			font-size: 20px;
			font-weight: 200;
			border-left: 1px solid #d1e2ff;
		}
	</style>

</head>
<body>
	<div class="inbox">
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>This is an inbox layout.</p>
		</div>
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>Check one item</p>
		</div>
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>Hold down your Shift key</p>
		</div>
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>Check a lower item</p>
		</div>
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>Everything inbetween should also be set to checked</p>
		</div>
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>Try do it with out any libraries</p>
		</div>
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>Just regular JavaScript</p>
		</div>
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>Good Luck!</p>
		</div>
		<div class="item">
			<input type="checkbox" name="" id="" />
			<p>Don't forget to tweet your result!</p>
		</div>
	</div>

	<script type="text/javascript">
		const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"');

		let lastChecked;
		let onOff = false;

		function handleCheck (e) {
			let inBetween = false;

			if (e.shiftKey) {
				checkboxes.forEach(checkbox => {
					console.log(checkbox);

					if (checkbox === this || checkbox === lastChecked) {

						inBetween = !inBetween;
						console.log('Starting to check them inbetween!');

						checkbox.checked = onOff;
					}

					if (inBetween && checkbox != this && checkbox !=lastChecked) {
						checkbox.checked = onOff;
					}

				});
			}

			lastChecked = this;
			onOff = this.checked;
		}

		checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));
	</script>
</body>
</html>